<template>
  <div class="main-container">
    <!-- 顶部导航 -->
    <HeaderBar 
      :user="user" 
      @logout="$emit('logout')"
      @profile-updated="handleProfileUpdated"
    />
    
    <div class="main-content">
      <!-- 左侧日期筛选 -->
      <aside class="sidebar">
        <DateFilter
          :selected="selectedDateFilter"
          :custom-date="customSelectedDate"
          @change="handleDateFilterChange"
        />
        <TodoStatistics 
          :statistics="filteredStatistics" 
          :date-filter="selectedDateFilter"
          :custom-date="customSelectedDate"
        />
        <AiSummary />
      </aside>
      
      <!-- 右侧主要内容 -->
      <main class="content">
        <!-- 快速添加 -->
        <QuickAdd
          ref="quickAddRef"
          @add-todo="handleAddTodo"
        />
        
        <!-- 待办事项列表 -->
        <TodoList
          :todos="filteredTodos"
          :loading="todosLoading"
          @complete="handleCompleteTodo"
          @delete="handleDeleteTodo"
          @edit="handleEditTodo"
        />
      </main>
    </div>
    
    <!-- 编辑对话框 -->
    <TodoDialog
      v-model="showEditDialog"
      :todo="editingTodo"
      @save="handleSaveTodo"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import HeaderBar from '../components/HeaderBar.vue'
import DateFilter from '../components/DateFilter.vue'
import TodoStatistics from '../components/TodoStatistics.vue'
import QuickAdd from '../components/QuickAdd.vue'
import TodoList from '../components/TodoList.vue'
import TodoDialog from '../components/TodoDialog.vue'
import AiSummary from '../components/AiSummary.vue'
import { 
  getTodosGroupByDate, 
  getTodoStatistics, 
  createTodo, 
  updateTodo, 
  completeTodo, 
  deleteTodo,
  getTodosByDate
} from '../api/todo'
import { getToday, getTomorrow, getDayAfterTomorrow, getYesterday } from '../utils/date'

export default {
  name: 'MainView',
  components: {
    HeaderBar,
    DateFilter,
    TodoStatistics,
    QuickAdd,
    TodoList,
    TodoDialog,
    AiSummary
  },
  props: {
    user: {
      type: Object,
      required: true
    }
  },
  emits: ['logout', 'profile-updated'],
  setup(props, { emit }) {
    const quickAddRef = ref()
    const todosLoading = ref(false)
    const selectedDateFilter = ref('today')
    const customSelectedDate = ref('')
    const showEditDialog = ref(false)
    const editingTodo = ref(null)
    
    // 待办事项数据（按日期分组）
    const todos = reactive({
      yesterday: [], // 昨天的待办事项
      today: [],     // 今天的待办事项
      tomorrow: [],  // 明天的待办事项
      dayAfterTomorrow: [], // 后天的待办事项
      custom: []     // 自定义日期的待办事项
    })
    
    // 统计数据
    const statistics = ref({
      pendingCount: 0,
      completedCount: 0,
      todayCount: 0,
      totalCount: 0
    })
    
    // 根据筛选条件过滤待办事项
    const filteredTodos = computed(() => {
      return todos[selectedDateFilter.value] || []
    })
    
    // 计算当前筛选条件下的统计数据
    const filteredStatistics = computed(() => {
      const currentTodos = filteredTodos.value
      const totalCount = currentTodos.length
      const completedCount = currentTodos.filter(todo => todo.completed).length
      const pendingCount = currentTodos.filter(todo => !todo.completed).length
      
      // 根据筛选条件确定统计标签
      const getDateLabel = () => {
        switch (selectedDateFilter.value) {
          case 'yesterday':
            return '昨日任务'
          case 'today':
            return '今日任务'
          case 'tomorrow':
            return '明日任务'
          case 'dayAfterTomorrow':
            return '后日任务'
          case 'custom':
            if (customSelectedDate.value) {
              const customDateObj = new Date(customSelectedDate.value)
              const customDateStr = customDateObj.toLocaleDateString('zh-CN', { 
                month: 'short',
                day: 'numeric' 
              })
              return `${customDateStr}任务`
            }
            return '自定义日期任务'
          default:
            return '当前任务'
        }
      }
      
      return {
        pendingCount,
        completedCount,
        todayCount: totalCount, // 这里实际表示当前筛选日期的任务数
        totalCount,
        dateLabel: getDateLabel()
      }
    })
    
    // 加载待办事项
    const loadTodos = async () => {
      try {
        todosLoading.value = true
        const response = await getTodosGroupByDate()
        if (response.data.code === 200) {
          const data = response.data.data
          todos.yesterday = data.yesterday || []
          todos.today = data.today || []
          todos.tomorrow = data.tomorrow || []
          todos.dayAfterTomorrow = data.dayAfterTomorrow || []
        }
      } catch (error) {
        console.error('加载待办事项失败:', error)
        ElMessage.error('加载待办事项失败')
      } finally {
        todosLoading.value = false
      }
    }
    
    // 加载指定日期的待办事项
    const loadTodosByDate = async (date) => {
      try {
        todosLoading.value = true
        console.log('加载指定日期的待办事项:', date)
        
        // 调用后端API获取指定日期的待办事项
        const response = await getTodosByDate(date)
        if (response.data.code === 200) {
          todos.custom = response.data.data || []
        } else {
          ElMessage.error(response.data.message || '获取待办事项失败')
          todos.custom = []
        }
      } catch (error) {
        console.error('加载指定日期待办事项失败:', error)
        ElMessage.error('加载指定日期待办事项失败')
        todos.custom = []
      } finally {
        todosLoading.value = false
      }
    }
    
    // 加载统计数据
    const loadStatistics = async () => {
      try {
        const response = await getTodoStatistics()
        if (response.data.code === 200) {
          statistics.value = response.data.data
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    }
    
    /**
     * 处理日期筛选变化
     * @param {string} filter - 筛选类型（yesterday, today, tomorrow, dayAfterTomorrow, custom）
     * @param {string} customDate - 自定义日期（仅当filter为custom时使用）
     */
    const handleDateFilterChange = (filter, customDate) => {
      selectedDateFilter.value = filter
      
      if (filter === 'custom' && customDate) {
        // 处理自定义日期选择
        customSelectedDate.value = customDate
        loadTodosByDate(customDate)
      } else {
        // 处理预设日期选择（yesterday, today, tomorrow, dayAfterTomorrow）
        customSelectedDate.value = ''
        
        // 检查是否需要重新加载数据
        if (!todos[filter] || todos[filter].length === 0) {
          if (filter === 'yesterday') {
            // 昨天数据如果不存在，通过日期API获取
            const yesterday = getYesterday()
            loadTodosByDate(yesterday).then(() => {
              // 将获取到的数据分配给yesterday字段
              todos.yesterday = [...(todos.custom || [])]
            })
          } else {
            // 其他预设日期通过分组API获取
            loadTodos()
          }
        }
      }
    }
    
    // 处理添加待办事项
    const handleAddTodo = async (todoData) => {
      try {
        const response = await createTodo(todoData)
        if (response.data.code === 200) {
          ElMessage.success('添加成功')
          await loadTodos()
          await loadStatistics()
          
          // 清空输入框并重新聚焦
          nextTick(() => {
            quickAddRef.value?.focusInput()
          })
        } else {
          ElMessage.error(response.data.message || '添加失败')
        }
      } catch (error) {
        console.error('添加待办事项失败:', error)
        ElMessage.error('添加失败')
      }
    }
    
    // 处理完成待办事项
    const handleCompleteTodo = async (todoId) => {
      try {
        const response = await completeTodo(todoId)
        if (response.data.code === 200) {
          ElMessage.success('任务已完成')
          await loadTodos()
          await loadStatistics()
        } else {
          ElMessage.error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('完成待办事项失败:', error)
        ElMessage.error('操作失败')
      }
    }
    
    // 处理删除待办事项
    const handleDeleteTodo = async (todoId) => {
      try {
        const response = await deleteTodo(todoId)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          await loadTodos()
          await loadStatistics()
        } else {
          ElMessage.error(response.data.message || '删除失败')
        }
      } catch (error) {
        console.error('删除待办事项失败:', error)
        ElMessage.error('删除失败')
      }
    }
    
    // 处理编辑待办事项
    const handleEditTodo = (todo) => {
      editingTodo.value = { ...todo }
      showEditDialog.value = true
    }
    
    // 处理保存待办事项
    const handleSaveTodo = async (todoData) => {
      try {
        const response = await updateTodo(todoData)
        if (response.data.code === 200) {
          ElMessage.success('更新成功')
          showEditDialog.value = false
          editingTodo.value = null
          await loadTodos()
          await loadStatistics()
        } else {
          ElMessage.error(response.data.message || '更新失败')
        }
      } catch (error) {
        console.error('更新待办事项失败:', error)
        ElMessage.error('更新失败')
      }
    }
    
    // 键盘快捷键处理
    const handleKeydown = (event) => {
      // Ctrl + N 聚焦输入框
      if (event.ctrlKey && event.key === 'n') {
        event.preventDefault()
        quickAddRef.value?.focusInput()
      }
      
      // Ctrl + 上/下切换日期视图
      if (event.ctrlKey && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
        event.preventDefault()
        const filters = ['yesterday', 'today', 'tomorrow', 'dayAfterTomorrow']
        const currentIndex = filters.indexOf(selectedDateFilter.value)
        let newIndex
        
        if (event.key === 'ArrowUp') {
          newIndex = currentIndex > 0 ? currentIndex - 1 : filters.length - 1
        } else {
          newIndex = currentIndex < filters.length - 1 ? currentIndex + 1 : 0
        }
        
        selectedDateFilter.value = filters[newIndex]
      }
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadTodos()
      loadStatistics()
      
      // 绑定键盘事件
      document.addEventListener('keydown', handleKeydown)
      
      // 聚焦输入框
      nextTick(() => {
        quickAddRef.value?.focusInput()
      })
    })
    
    // 处理个人资料更新
    const handleProfileUpdated = (updatedUser) => {
      emit('profile-updated', updatedUser)
    }
    
    // 组件卸载时移除键盘事件
    onUnmounted(() => {
      document.removeEventListener('keydown', handleKeydown)
    })
    
    return {
      quickAddRef,
      todosLoading,
      selectedDateFilter,
      customSelectedDate,
      showEditDialog,
      editingTodo,
      filteredTodos,
      statistics,
      filteredStatistics,
      handleDateFilterChange,
      handleAddTodo,
      handleCompleteTodo,
      handleDeleteTodo,
      handleEditTodo,
      handleSaveTodo,
      handleProfileUpdated
    }
  }
}
</script>

<style scoped>
.main-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 24px;
  padding: 16px 20px;
  max-width: 95%;
  margin: 0 auto;
  width: 100%;
}

.sidebar {
  width: 350px;
  flex-shrink: 0;
}

.content {
  flex: 1;
  min-width: 0;
}

/* 大屏幕适配 */
@media (min-width: 1920px) {
  .main-content {
    max-width: 98%;
    padding: 16px 24px;
  }
  
  .sidebar {
    width: 400px;
  }
}

@media (min-width: 1440px) and (max-width: 1919px) {
  .main-content {
    max-width: 96%;
  }
  
  .sidebar {
    width: 380px;
  }
}

@media (min-width: 1200px) and (max-width: 1439px) {
  .main-content {
    max-width: 94%;
  }
  
  .sidebar {
    width: 350px;
  }
}

@media (max-width: 1199px) {
  .main-content {
    max-width: 92%;
    padding: 16px;
  }
  
  .sidebar {
    width: 320px;
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    padding: 12px;
    gap: 16px;
    max-width: 100%;
  }
  
  .sidebar {
    width: 100%;
  }
}
</style> 